<?php
$isReloadable = false;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');
require_once('../../_inc/funct.tabDati.php');

$sql_sel = "SELECT  m.cod_mod_rbil, m.descr AS m_descr " 
		." FROM rgl_mod_rbil m " 
		." WHERE m.id_mod_rbil = ".reqVarInt('id')
		;
$objDB->query($sql_sel,'selRec');
if (!$acX = $objDB->fetch('selRec')) {
	die ('parIndImport - no id. '.reqVar('id'));
}

$aExp = array();
if (reqVar('azione')=='upload')  {
	$msgPag .= uploadParInd($aExp);
}
if (reqVar('azione')=='aggi' || reqVar('azione')=='sost')  {
	$msgPag .= importParInd($aExp, $aParInd);
}

$cmdL = "";

$cmdR = '';
if (reqVar('file_caricato')!='') { 
	$cmdR .= "&nbsp;&nbsp;&nbsp;";
	$cmdR .= "<a class=\"cmd1\" href=\"javascript:submAz('sost');\">sostituisci</a>";
		$cmdR .= "&nbsp;&nbsp;&nbsp;";
	$cmdR .= "<a class=\"cmd1\" href=\"javascript:submAz('aggi');\">aggiungi</a>";
}
$cmdR .= cmdTorna(); 
testaHtml('Gestione modelli', $msgPag, 'modl');
echo getHtmlForm();
echo getHtmlHidden('xsn',XSN);
echo getHtmlHidden('azione','...');
echo getHtmlHidden('id');
echo getHtmlHidden('file_caricato');
echo getHtmlHidden('file_orig');
?>
<script language="JavaScript" type="text/javascript">
  	function submAz(az) {
  		document.frm1.azione.value = az;
  		document.frm1.submit();
  	}
</script>
<table class="cmd1" border="0" cellpadding="3" cellspacing="1" width="100%">
   <tr>
      <td class="cmd1" align="left">
         <?=$cmdL?>
      </td>
      <td class="cmd1" align="right">
         <?=$cmdR?>
      </td>
   </tr>
</table>
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%">
   <tr>
      <td class="tit1" colspan='2'>Importazione soglie indici di bilancio</td>
   </tr>
   <tr>
      <td class="lab1" align="left" width='10%'>Modello</td>
      <td class="txt1" align="left" width='90%'>
         <?=$acX['cod_mod_rbil']." - ".$acX['m_descr']?>
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='1' align='left'>File parind_xxx.ser</td>
      <td class="txt1" colspan='1' align='left'>
<?
echo getHtmlFile('file_ser', 80);
echo "&nbsp;&nbsp;&nbsp;";
if (reqVar('file_caricato')=='') { 
	echo "<a class=\"cmd1\" href=\"javascript:submAz('upload');\">upload</a>";
} else {
	echo "<a class=\"cmd1\" href=\"javascript:submAz('upload');\">nuovo upload</a>";
}
?>
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='1'  width='20%'>File caricato</td>
      <td class="txt1" colspan='1'  width='80%'>
      	<?=reqVar('file_orig');?>
      </td>
   </tr>
<?
if (is_array($aExp) && count($aExp) > 0) {
?>
   <tr>
      <td class="lab1" colspan='1'>Data export</td>
		<td class="txt1" colspan='1'><?=date('d/m/y H:i',$aExp['head']['data_ora'])?></td>
	</tr>
   <tr>
      <td class="lab1" colspan='1'>Servert</td>
		<td class="txt1" colspan='1'><?=$aExp['head']['server']?></td>
	</tr>
   <tr>
      <td class="lab1" colspan='1'>Data base</td>
		<td class="txt1" colspan='1'><?=$aExp['head']['data_base']?></td>
	</tr>
   <tr>
      <td class="lab1" colspan='1'>Mod. rating bil. orig.</td>
		<td class="txt1" colspan='1'><?=$aExp['head']['cod']?></td>
	</tr>
<?
}
?>
</table>
<table class="cmd1" border="0" cellpadding="3" cellspacing="1" width="100%">
   <tr>
      <td class="cmd1" align="left">
         <?=$cmdL?>
      </td>
      <td class="cmd1" align="right">
         <?=$cmdR?>
      </td>
   </tr>
</table>
<?
echo "</form>\n";
codaHtml();
exit();

function importParInd(&$aExp, $aParInd) {
	global $objDB, $objSess;
	$msg = '';
	$aExp = unserialize(gzuncompress(file_get_contents(RGL_FS_TEMP_DIR."/".reqVar('file_caricato'))));
	if (!is_array($aExp)
	|| !isset($aExp['head'])
	|| !isset($aExp['head']['tipo'])) {
		$_REQUEST['file_caricato'] = '';
		return "file non conforme o corrotto<br>";
	}
	if ($aExp['head']['tipo'] != 'parind') {
		$_REQUEST['file_caricato'] = '';
		return "file importazione '".$aExp['head']['tipo']."' - atteso 'parind'<br>";
	}
	if ($msg!='') return $msg;

	$sql_sel = "SELECT d.cod_dato, d.descr FROM rgl_mod_rbil mb " 
		." INNER JOIN rgl_def_dato d ON d.id_set_dati = mb.id_set_dati "
		."    AND d.tipo_tab_dati = mb.tipo_tab_indici "
		." WHERE mb.id_mod_rbil = ".reqVarInt('id')
		."   AND d.tipo_valore <> 'label'"
		." ORDER BY d.cod_dato "
		;
	$objDB->query($sql_sel,'selRec');
	$aCodDato = array();
	while($acX = $objDB->fetch('selRec')) {
		$aCodDato[] = $acX['cod_dato'];
	}
	$aDatiManc = array();
	if (reqvar('azione')=='sost') {
		$sSql = "DELETE FROM rgl_mod_rbil_par_ind "
			." WHERE id_mod_rbil = ".reqVarInt('id');
		$objDB->query($sSql);
		$msg .= "Eliminati ".$objDB->affectedRec()." elementi<br>";
	}
	$nnIns = 0;
	$nnUpd = 0;
	foreach($aExp['body']['parind'] as $kX => $aX) {
		if (!in_array($aX['cod_dato'],$aCodDato)) {
			$aDatiManc[] = $aX['cod_dato'];
			continue;
		}
		$sSql = "SELECT * FROM rgl_mod_rbil_par_ind "
			." WHERE id_mod_rbil = ".reqVarInt('id')
			."    AND cod_sett = '".$aX['cod_sett']."'"
			."    AND cod_dato = '".$aX['cod_dato']."'";
			$objDB->query($sSql);
		if ($acPI=$objDB->fetch()) {
			$sSql = 'UPDATE rgl_mod_rbil_par_ind SET ';
			foreach($aX as $nC => $vC) {
				if ($nC=='id_mod_rbil') continue;
				if ($nC=='cod_sett') continue;
				if ($nC=='cod_dato') continue;
				if ($nC=='cod_mod_rbil') continue;
				$sSql .= $nC." = '".addslashes($vC)."', ";
			}
			$sSql = substr($sSql,0,-2)." WHERE id_mod_rbil = ".reqVarInt('id')
			."    AND cod_sett = '".$aX['cod_sett']."'"
			."    AND cod_dato = '".$aX['cod_dato']."'";
			$objDB->exec($sSql);
			$nnUpd++;
		} else {
			$sSql = 'INSERT INTO rgl_mod_rbil_par_ind SET ';
			foreach($aX as $nC => $vC) {
				if ($nC=='cod_mod_rbil') continue;
				if ($nC=='id_mod_rbil') {
					$vC =  reqVarInt('id');
				}
				$sSql .= $nC." = '".addslashes($vC)."', ";
			}
			$sSql = substr($sSql,0,-2);
			$objDB->exec($sSql);
			$nnIns++;
		}
	}
	$msg .= "Inseriti $nnIns elementi<br>";
	$msg .= "Sostituiti $nnUpd elementi<br>";
	if (count($aDatiManc)>0) {
		$msg .= "Dati inesistenti: ".implode(', ',$aDatiManc)."<br>";
	}
	return $msg;
}

function uploadParInd(&$aExp) {
	global $objDB, $objSess;
	$aExp = array();
	if (!isset($_FILES['file_ser']) || $_FILES['file_ser']['tmp_name'] == '') {
		$_REQUEST['file_caricato'] = '';
		$_REQUEST['file_orig'] = '';
		return "nessun file caricato<br>";
	}
	$dh = opendir(RGL_FS_TEMP_DIR);
	while($fn = readdir($dh)) {
		if (substr($fn,0,14)=='parind_import_'
		&& filemtime(RGL_FS_TEMP_DIR."/".$fn) < (time()-3600*24)) {
			unlink(RGL_FS_TEMP_DIR."/".$fn);
		}
	}
	$_REQUEST['file_orig'] = $_FILES['file_ser']['name'];
	$aExp = unserialize(gzuncompress(file_get_contents($_FILES['file_ser']['tmp_name'])));
	if (!is_array($aExp)
	|| !isset($aExp['head'])
	|| !isset($aExp['head']['tipo'])) {
		$_REQUEST['file_caricato'] = '';
		return "file non conforme o corrotto<br>";
	}
	if ($aExp['head']['tipo'] != 'parind') {
		$_REQUEST['file_caricato'] = '';
		return "file importazione '".$aExp['head']['tipo']."' - atteso 'parind'<br>";
	}
	$fileCar = "parind_import_".uniqid();
	$pathFileCar = RGL_FS_TEMP_DIR."/".$fileCar;
	copy($_FILES['file_ser']['tmp_name'],$pathFileCar);
	$_REQUEST['file_caricato'] = $fileCar;
	$_REQUEST['file_orig'] = $_FILES['file_ser']['name'];
	return "file caricato<br>";
}
